function imgs = readimages(dirpath, spec, fun)
%READIMAGES Reads a collection of images from a directory
%
%   imgs = READIMAGES(dirpath, globpat);
%
%       Reads images from the specified directory, whose filenames
%       are specified in form of glob pattern. 
%
%       For example, to read all jpeg images in the directory /usr/abc,
%       one can write
%
%           imgs = READIMAGES('/usr/abc', '*.jpg');
%
%       The output argument imgs is a cell array, with each cell 
%       containing an image.
%
%   imgs = READIMAGES(dirpath, {cformat, indices});
%
%       Reads images from the specified directory, with filenames given
%       in form of C-format (i.e. the format used in sprintf).
%
%       For example, to read the images (from 0001.jpg to 3000.jpg) in 
%       /usr/abc, one can write
%
%           imgs = READIMAGES('/usr/abc', {'%04d.jpg', 1:3000});
%
%
%   imgs = READIMAGES(dirpath, spec, fun);
%
%       Reads the images from files and transforms them using the given 
%       function.
%
%       For example, to read the images and converts them into gray-scale,
%       one can write
%
%           imgs = READIMAGES('/usr/abc', '*.jpg', @rgb2gray);
%       
%

% Created by Dahua Lin, on Mar 8, 2012
% Modified by Dahua Lin, on Mar 21, 2012
%

%% verify input arguments

if ~ischar(dirpath)
    error('readimages:invalidarg', 'dirpath should be a char string.');
end

if nargin < 3
    use_fun = 0;
else
    if ~isa(fun, 'function_handle')
        error('readimages:invalidarg', 'fun should be a function handle.');
    end
    use_fun = 1;
end
        
%% main

% generate filenames

if ischar(spec)
    fns = dir(fullfile(dirpath, spec));
    fns = {fns.name};
    
elseif iscell(spec) && numel(spec) == 2
    
    cpat = spec{1};
    indices = spec{2}; 
    
    if ~(ischar(cpat) && isnumeric(indices))
        error('readimages:invalidarg', ...
            'the filename specification is invalid.');
    end
    
    fns = arrayfun(@(i) sprintf(cpat, i), indices, 'UniformOutput', false);
end

n = numel(fns);

imgs = cell(n, 1);


for i = 1 : n
    fp = fullfile(dirpath, fns{i});
    I = imread(fp);
    if use_fun
        I = fun(I);
    end
    imgs{i} = I;
end


